<script setup lang="ts">
import type { CascaderProps } from 'ant-design-vue';

import { onMounted, ref, watchEffect } from 'vue';

import { DictEnum } from '@vben/constants';

import { Cascader } from 'ant-design-vue';

import { dataSourceInfo, dataSourceList } from '#/api/company/source';
import { dictDataInfo } from '#/api/system/dict/dict-data';

defineOptions({ name: 'SourceCascader' });

withDefaults(defineProps<Props>(), {
  disabled: false,
  placeholder: '请选择',
  allowClear: true,
});

const emit = defineEmits(['blur', 'change']);

interface Props {
  disabled?: boolean;
  placeholder?: string;
  allowClear?: boolean;
}

const options = ref<CascaderProps['options']>([]);

const modelValue = defineModel<string>('value', {
  default: undefined,
});

const bindValue = ref<string[]>([]);
const inited = ref(false);
watchEffect(() => {
  if (modelValue.value) {
    console.log('来源级联组件watchEffect变化', modelValue.value);
    if (!inited.value) {
      init();
    }
  } else {
    bindValue.value = [];
  }
});

async function loadData(selectedOptions: any) {
  inited.value = true;
  console.log('来源级联组件触发loadData', selectedOptions);
  const targetOption = selectedOptions[selectedOptions.length - 1];
  targetOption.loading = true;

  // 加载来源列表数据
  await loadChildren(targetOption.value, targetOption);
  targetOption.loading = false;
}

// 查询来源类型字典
async function loadTypeDict() {
  const list = await dictDataInfo(DictEnum.DATA_SOURCE_TYPE);
  options.value = list.map((item) => {
    // 标记是否为叶子节点，设置了 `loadData` 时有效
    // 设为 `false` 时会强制标记为父节点，即使当前节点没有 children，也会显示展开图标
    return { label: item.dictLabel, value: +item.dictValue, isLeaf: false };
  });
}

// 查询来源列表
async function loadChildren(type: any, targetOpt: any) {
  const list = type ? await dataSourceList({ type, status: '0' }) : [];
  const targetOption =
    targetOpt || options.value?.find((item) => item.value === type);
  if (targetOption) {
    if (list.length > 0) {
      targetOption.children = list.map((item) => {
        return { label: item.name, value: item.id, isLeaf: true };
      });
    } else {
      // targetOption.isLeaf = true;
      targetOption.isLeaf = false;
    }
  }
}

onMounted(async () => {
  console.log('来源级联组件onMounted:', modelValue.value);
  await loadTypeDict();
});

async function init() {
  if (modelValue.value) {
    // 初始化有默认值时，查询来源详情
    const sourceDetails = await dataSourceInfo(modelValue.value);
    if (sourceDetails?.id) {
      // 查找当前来源数据对应的来源类型父级option
      const targetOption = options.value?.find(
        (item) => item.value === sourceDetails.type,
      );
      if (targetOption) {
        await loadChildren(sourceDetails.type, targetOption);
        bindValue.value = [targetOption.value as string, modelValue.value];
      }
    }
  }
}

function handleChange() {
  console.log('来源级联组件触发change:', bindValue.value);
  if (bindValue.value.length > 1) {
    modelValue.value = bindValue.value[1] as string;
    emit('change', bindValue.value[1]);
  }
}
</script>

<template>
  <div class="flex w-full gap-1">
    <Cascader
      v-model:value="bindValue"
      :options="options"
      :load-data="loadData"
      class="w-full"
      :placeholder="placeholder"
      :change-on-select="false"
      :allow-clear="allowClear"
      @blur="emit('blur')"
      @change="handleChange"
    />
  </div>
</template>
